﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Test.Api;

namespace SwaggerDoc.Api.Controllers
{
    /// <summary>
    /// 账号控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class AccountController : ControllerBase
    {
        private IOptions<JwtOption> _option;
        /// <summary>
        /// AccountController
        /// </summary>
        /// <param name="option"></param>
        public AccountController(IOptions<JwtOption> option)
        {
            _option = option;
        }
        /// <summary>
        /// 登入
        /// </summary>
        /// <param name="loginModel"></param>
        /// <returns></returns>
        [HttpPost("Login")]
        [AllowAnonymous]
        public IActionResult Login(LoginModel loginModel)
        {
            if (loginModel.Name == "admin" && loginModel.Password == "admin")
            {
                var claims = new[]
                {
                     new Claim(ClaimTypes.Name, loginModel.Name),
                     new Claim(ClaimTypes.Role, "admin"),
                     new Claim(JwtRegisteredClaimNames.Jti, loginModel.Name??""),
                };

                var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_option.Value.SecretKey));
                var algorithm = SecurityAlgorithms.HmacSha256;
                var signingCredentials = new SigningCredentials(secretKey, algorithm);
                var jwtSecurityToken = new JwtSecurityToken(
                    _option.Value.Issuer,     //Issuer
                    _option.Value.Audience,   //Audience
                    claims,                          //Claims,
                    DateTime.Now,                    //notBefore
                    DateTime.Now.AddDays(_option.Value.Expire),//expires
                    signingCredentials              //Credentials
                );

                var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

                return Ok(token);
            }
            else
            {
                return BadRequest();
            }
        }
        /// <summary>
        /// 用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("Info")]
        public IActionResult Info()
        {
            return Ok(new
            {
                Name = "admin"
            });
        }
    }
}
